﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using zqdn.Models.Auth;
using zqdn.Models.ProvinceCity;
using zqdn.Services.Auth;
using zqdn.Services.Interfaces.ProvinceCity;
using zqdn.Web.App_Start;
using zqdn.Web.ViewModels;
using zqdn.Web.Filters;
using zqdn.Services.Interfaces.CommonCenter;
using zqdn.Repositories.Interfaces.Auth;

namespace zqdn.Web.Controllers
{
    public class UserController : Controller
    {
        private readonly IUserService _userService;
        private readonly ICityDetailsService _cityDetailservice;
       
        public UserController(IUserService userService, ICityDetailsService cityDetailservice)
        {
           this._userService = userService;
           this._cityDetailservice = cityDetailservice;
        }

        #region 用户登陆
        // POST: User/Login
        [HttpPost]
        public JsonResult Login(UseriewModel model)
        {
            try
            {
                var re = _userService.UserLogin(model.UserName, model.Password,"",1); //登录只针对代表，医生使用openid直接绑定无需登录
                    if (re == null)
                        return Json(new { Result = "error", msg = "登录失败用户名或密码不正确" });
                   
                    var user = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<zqdn.Models.Auth.User, ViewModels.ApplicationUser>().Map(re);

                    SessionContext.SignIn(user);
    
                    return Json(new { Result = "success", Url = "", msg = "登录成功",userInfo= re });

             }
            catch (Exception ex)
            {
                return Json(new { Result = "error", Url = "", msg = ex.ToString() });
            }
        }
        #endregion


        public JsonResult check(string openid) {
            //GetUserByOprnID
            try {
                var re = _userService.GetUserByOprnID(openid);
                if (re != null) {
                    return Json(new { Result = "success", msg = "1", userInfo = re }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { Result = "error", Url = "", msg = "0" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", Url = "", msg = ex.ToString() }, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult getUserInfo(int id)
        {
            //GetUserByOprnID
            try
            {
                var re = _userService.GetUserByID(id);
                if (re == null)
                {
                    return Json(new { Result = "error", msg = "1" }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { Result = "success", Url = "", msg = "0" ,userInfo = re }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", Url = "", msg = "系统异常" }, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult getDoctorInfo(string openid)
        {
            //GetUserByOprnID
            try
            {
                var re = _userService.GetUserByOprnID(openid);
                var docfilter = _userService.getDoctorByMobile(re.Mobile);
                //var re = _userService.getDoctorByMobile(mobile);
                if (docfilter == null)
                {
                    return Json(new { Result = "error", msg = "您的权限尚未开通，请耐心等待，谢谢！" }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { Result = "success", Url = "", msg = "0", userInfo = docfilter }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", Url = "", msg = "系统异常" }, JsonRequestBehavior.AllowGet);
            }
        }




        #region 用户注册
        // GET: User/Register
        public ActionResult Register()
        {
            //该类数据均从数据库中读取
            ViewBag.province = new ApiController().SetOptionItem(new ApiController().GetProvince(),null);
            ViewBag.city = new ApiController().SetOptionItem(new List<CityDetails>(),null);
            ViewBag.hospital = new ApiController().SetOptionItem(new List<Hospital>(),null);
            return View();
        }


        [HttpPost]
        public JsonResult Register(UseriewModel model)
        {
            try
            {
                //判断验证码是否正确
               // if (model.VerifyCode != "1234")   //Session["RegitCode"].ToString()
                  // return Json(new { Result = "error", msg = "验证码不正确，请仔细核对！" });

                //判断数据库中是否已存在此用户
                var re = _userService.GetUserByMobile(model.Mobile);
                if (re != null)
                {
                    return Json(new { Result = "error", msg = "注册失败,该手机号已存在!" });
                }

                //判断用户名是否合法
                //if (ModelState.IsValid)
               //{
                    User user = new User
                    {
                        Name = model.Name,
                        UserName = model.Mobile,
                        PassWord = Utils.Security.Encrypt.Md5Encrypt(model.Mobile.Substring(model.Mobile.Length - 6, 6)),///默认为手机号后六位
                        RoleID = 1,
                        Mobile = model.Mobile,
                        CreatedTime = DateTime.Now,
                        ModifiedTime = DateTime.Now,
                        Area = model.Area,
                        Province = model.Province,
                        City = model.City,
                        Hospital = model.Hospital,
                        Deparment = model.Deparment,
                        OpenId = model.OpenId,
                        NikeName = model.NikeName,
                        HeadImg = model.HeadImg,
                        Status = 0,
                        IsDeleted = false
                     };
                    _userService.AddUser(user);
                    _userService.UserLogin(model.UserName, model.Password, model.OpenId, 2);  //医生openID绑定登录
                    return Json(new { Result = "success", msg = "注册成功" });
                //}
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.ToString() });
            }
        }
 
        #endregion

        #region 注销
        public JsonResult Logout()
        {
            SessionContext.SignOut();
            return Json(new { Result = "error", Url = "", msg = "注销成功" });
        }
        #endregion

        #region 修改用户信息
        public ActionResult Information()
        {
            if (SessionContext.CurrentUser == null)
            {
                return RedirectToAction("Login", "User");
            }
            else
            {
                var re = _userService.GetUserByID(SessionContext.CurrentUser.ID);
               // ViewBag.province = _cityDetailservice.GetByID(re.Province).Name;
                //ViewBag.city = _cityDetailservice.GetByID(re.City).Name;
                //ViewBag.hospital = _cityDetailservice.GetHospitalByID(re.Hospital).Name;
                return View(re);
            }
        }
        [HttpPost]
        public ActionResult Information(FormCollection collection)
        {
            try
            {
                var re = _userService.GetUserByID(SessionContext.CurrentUser.ID);
                if (re.PassWord != Utils.Security.Encrypt.Md5Encrypt(collection["oldpassword"]))
                {
                    return Json(new { Result = "error", msg = "原始密码错误!" });
                }
                else
                {
                    re.PassWord = Utils.Security.Encrypt.Md5Encrypt(collection["PassWord"]);
                    _userService.UpdateUser(re);
                    return Json(new { Result = "success", Url = Url.Action("index", "doccenter"), msg = "修改成功！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.Message });
            }
          
        }
        #endregion

        [HttpPost]
        public ActionResult updateIntegral(UserieScourewModel model)
        {
            try
            {
                var re = _userService.GetUserByOprnID(model.openID);
                re.Integral = re.Integral + model.Integral;
                _userService.UpdateUser(re);
                return Json(new { Result = "success", msg = "恭喜你完成", userInfo = re });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.Message });
            }

        }

        #region 用户中心
        public ActionResult UserCenter()
        {
            if (SessionContext.CurrentUser == null)
            {
                return RedirectToAction("Login", "User");
            }
            else
            {
                var reurl = "";
               
                return Redirect(reurl);
            }
        }
        #endregion

    }

}